package com.moioo.vod;

import javax.servlet.http.*;
import javax.servlet.*;

/*
 * @author rivery 
 */
import java.util.List;
import java.io.*;
import java.net.*;

public class FileServer extends HttpServlet {
	
	public void init(ServletConfig config) throws ServletException{
		ServerThread st=new ServerThread(config);
		st.start();
	}
	public class ServerThread extends Thread
	{
		private ServletConfig config;
		public ServerThread(ServletConfig config)
		{
			this.config=config;
		}
		public void run()
		{
			int port=Integer.parseInt(config.getInitParameter("Port"));
			try
			{
				ServerSocket server=new ServerSocket(port);
				while(true)
				{
					Socket conn=server.accept();
					FileThread f=new FileThread(conn);
					f.start();
				}
			}catch(Exception e)
			{}
		}
	}
	public class FileThread extends Thread
	{
		private Socket conn;
		public FileThread(Socket conn)
		{
			this.conn=conn;
		}
		public void run()
		{
			DataInputStream in=null;
			DataOutputStream out=null;
			FileOutputStream fw=null;
			String filename=null;
			long filelength=0;
			try
			{
				in=new DataInputStream(this.conn.getInputStream());
				out=new DataOutputStream(this.conn.getOutputStream());
				int i=in.readInt();
				if (i!=19771010)return;
				int len=in.readInt();
				byte buf[]=new byte[len];
				int length=0;
				while(length<len)
				{
					i=in.read(buf,length,len-length);
					if (i>0)length+=i;
				}
				filename=com.moioo.vod.Vod.ActionPath+File.separatorChar+"file"+File.separatorChar+new String(buf);
				fw=new FileOutputStream(filename);
				out.writeInt(19800330);
				filelength=in.readLong();
				long filelen=0;
				buf=new byte[4096];
				while(filelen<filelength)
				{
					i=in.read(buf);
					if (i>0)
					{
						fw.write(buf,0,i);
						fw.flush();
						filelen+=i;
					}
				}
			}catch(Exception e)
			{
				
			}finally
			{
				try
				{
					fw.close();
					fw=null;
				}catch(Exception e){}
				if (filename!=null)
				{
					File f=new File(filename);
					if (f.length()!=filelength)
					{
						f.delete();
					}
				}
				try
				{
					in.close();
					in=null;
				}catch(Exception e){}				
				try
				{
					out.close();
					out=null;
				}catch(Exception e){}
				try
				{
					this.conn.close();
					this.conn=null;
				}catch(Exception e){}
			}
		}
	}
  }